﻿namespace DCHealthCheck.MvcWeb {

    #region Usings
    using DCHealthCheck.Common;
    using DCHealthCheck.MvcWeb.Classes;
    using DCHealthCheck.MvcWeb.Classes.ViewModels;
    using SimpleInjector;
    using SimpleInjector.Integration.Web.Mvc;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading;
    using System.Web;
    using System.Web.Http;
    using System.Web.Mvc;
    using System.Web.Optimization;
    using System.Web.Routing; 
    #endregion

    public class MvcApplication : System.Web.HttpApplication {

        protected void Application_Start() {
            log4net.Config.XmlConfigurator.Configure();
            Global.DefaultLog.InfoFormat("[ThreadId: {0}] {1} ", Thread.CurrentThread.ManagedThreadId, Extensions.CurrentMethodName());

            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            // Custom ModelBinder
            ModelBinders.Binders.DefaultBinder = new CustomViewModelBinder();

            this.Error += new EventHandler(MvcApplication_Error);

            try {
                Global.Initialize();
            }
            catch (Exception ex) {
                Global.DefaultLog.FatalFormat("Application Failed to Start: ", ex.VerboseExceptionString());
                Global.ApplicationUnavailable = true;
            }
        }

        /// <summary>
        /// For non-http request unhandled exceptions.  The BaseController.OnException() should handle http errors.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void MvcApplication_Error(object sender, EventArgs e) {
            Exception exception = Server.GetLastError() as Exception;

            Global.DefaultLog.ErrorFormat("[ThreadId: {0}] {1} {2}", Thread.CurrentThread.ManagedThreadId, Extensions.CurrentMethodName(), exception.VerboseExceptionString());
        }
    }
}